<template>
  <div>
  	<!-- 此处注意写法v-model:content -->
    <QuillEditor ref="quillEditorRef"

      class="myQuillEditor"
      theme="snow"
      contentType="html"
      v-model:content="editorContent"
      :options="data.editorOption"
      @update:content="handleUpdate()"
    />
    <!-- 使用自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png,.jpeg" ref="fileBtn" @change="handleUpload" />
  </div>
</template>

<script setup>
import { Quill, QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { reactive, onMounted, ref, toRaw, watch, computed, onUpdated } from 'vue'
// import BlotFormatter from 'quill-blot-formatter'
// Quill.register("modules/blotFormatter", BlotFormatter)
import axios from 'axios'
import { localGet } from '@/utils'

// const modules = {
//   module: BlotFormatter,
// }
// let quillInstance = null
const props = defineProps({
  height: {
    type: Number,
    default:500
  },
  content: {
    type: String,
    default: ''
  },
})

const editorContent = computed({
  get: () => props.content,
  set: (val) => {
    emit('update:content', val);
  }
})
const emit = defineEmits(['update:content', 'updateValue']);
// const emit = defineEmits(['updateValue'])
const content = ref('')
const quillEditorRef = ref()

const fileBtn = ref()
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image'],
        [{ 'direction': 'rtl' }],
        [{ 'color': [] }, { 'background': [] }]
      ]
    },
    placeholder: '请输入内容...'
  }
})
const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}

const handleUpload = (e) => {
  const files = Array.prototype.slice.call(e.target.files)
  if (!files) {
    return
  }
  const formdata = new FormData()
  formdata.append('images', files[0])
  axios.post('/uploadImage/',formdata, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'token': localGet('token'),
      },
    }).then(res =>{
    if (res.code == 200){
      const quill = toRaw(quillEditorRef.value).getQuill()
      const length = quill.getSelection().index
      quill.insertEmbed(length, 'image', res.data.results)
      quill.setSelection(length + 1)
    }else{
      ElMessage.error("很遗憾，图片上传失败！")      
    }
  })
}
const handleUpdate = () => {
  //console.log(content, innerContent.value)
  const text=toRaw(quillEditorRef.value).getHTML()
  emit('updateValue', text)

  // let quill = quillEditorRef.value.getQuill()
  // console.log('quill实例：', quill)
  // const length = quill.getSelection().index
  // console.log('文本length:', length)
  // quill.setSelection(10, 0)

};
// 初始化编辑器
onMounted(() => {
  console.log('props.content:', props.content)
  toRaw(quillEditorRef.value).setHTML(props.content)
  const quill = toRaw(quillEditorRef.value).getQuill()
  if (quillEditorRef.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }
  
  // quillInstance = new Quill(quillEditorRef.value);
  // quillInstance.setContents(Quill.import('delta').decode(props.content));
  // quillInstance.on('text-change', (delta, oldDelta, source) => {
  //   const html = quillEditorRef.value.children[0].innerHTML;
  //   const text = quillInstance.getText();
  //   emit('update:content', quillInstance.root.innerHTML);
  //   // 可以根据需要进行扩展，比如处理图片上传等
  // });
})
onUpdated(() => {
  console.log('props.content:', props.content)
  toRaw(quillEditorRef.value).setHTML(props.content)
})
</script>
<style scoped lang="scss">
.myQuillEditor {
  margin: 1px;
}
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>